import React, { Component } from 'react';

import './index.less';

import App from 'layout/App.js'
import DateTime from '../WorkDataUseData/DateTime.jsx'
import { FormControl, Button, Icon, Table, Pagination, ProgressBar } from 'tinper-bee';
import RangePicker from '../../components/RangePicker/index.jsx'

import { vendorsSetUrl, vendorsTrimStr, vendorsDanger as danger, vendorsFmtDate, vendorsGetUrlParam } from 'utils/config.js';
import { getGroupQueryList } from './groupquery.config'


import jdiwork from '../../utils/jdiwork'
let tenantId;
let cookieStr = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1)
if(cookieStr){
    tenantId = cookieStr.split('=')[1];
}
// tenantId = "x61tnmfx";
export default class GroupQuery extends Component {
    constructor(props) {
        super(props);
        let _self = this;
        this.state = {
            startTime:'',
            endTime:'',
            searchValue: '',
            activePage: 1,
            billCount:0,
            picCount:0,
            start:0,
            count:0,
            limit:10,
            columns: [
                {title: "排名", dataIndex: "num", key: "num", width: '5%',
                    render(text, record, index) {
                        return(
                            <span>{index+1}</span>
                        )
                    }
                },
                {title: "组织名称", dataIndex: "orgName", key: "orgName", width: '55%' ,
                    render(text, record, index) {
                        let span;
                        if(record.pkOrg){
                            span = <span style={{color:"#2C7EDC", cursor: "pointer"}} onClick={()=>{_self.handleOrgClick(record)}}>{text}</span>
                        }else {
                            span = <span>{text}</span>
                        }
                        return(
                            span
                        )
                    } },
                {title: "单据总数", dataIndex: "billCount", key: "billCount", width: '20%'},
                {title: "图片总数", dataIndex: "picCount", key: "picCount", width: '20%'},
            ],
            tableData: []
        }
    }
    handleGetGroupQueryList =(timeInfo)=>{
        let { searchValue, activePage, startTime, endTime, limit, start } = this.state;
        startTime = Date.parse(startTime);
        endTime = Date.parse(endTime);
        let param={
            tenantId,
            orgKeyword: searchValue,
            start:(activePage-1)*limit,
            limit,
            timeStart:startTime,
            timeEnd:endTime,
            ieStamp:new Date().getTime(),
            isAjax:1
        };
        if(timeInfo&&timeInfo.length){
            param={...param,timeStart:Date.parse(timeInfo[0]),timeEnd:Date.parse(timeInfo[1])}
        }
        getGroupQueryList(param).then((res)=>{
            let data=res.data;
            if (data.resultCode !=='busi_ex'){
                this.getTableData(data.result)
            } else {
                danger({'text':data.exMsg})
            }
        })
    };
    getTableData =(data)=>{
        let { limit, activePage }=this.state;
        let { billCount, orgInfo, picCount } = data;
        let { objects, count, pageStart } = orgInfo;
        let tableData = objects&&objects.length?objects:[];
        if((activePage-1)*limit==pageStart){
            this.setState({
                tableData,
                billCount,
                picCount,
                count,
                start: pageStart
            })
        }
    }
    componentDidMount() {
        if(tenantId){
            this.initGroupQueryData()
        }else {
            jdiwork().getContext((data) => {
                tenantId = data.tenantid
                this.initGroupQueryData()
            });
        }
    }
    initGroupQueryData =()=>{
        let copyFromGroupData = JSON.parse(sessionStorage.getItem('copyFromGroupData'));
        if(copyFromGroupData){
            let keysData = Object.keys(copyFromGroupData);
            if(keysData&&keysData.length){
                let startTime = vendorsFmtDate(copyFromGroupData['start_time']);
                let endTime = vendorsFmtDate(copyFromGroupData['end_time']);
                this.setState({
                    searchValue:copyFromGroupData['searchValue'],
                    endTime,
                    startTime,
                    activePage:copyFromGroupData['activePage']
                },()=>{
                    sessionStorage.clear('copyFromGroupData');
                    sessionStorage.clear('fromGroupData');
                    this.handleGetGroupQueryList()
                })
            }else {
                this.handleAutoTimeValue(this.handleGetGroupQueryList)
            }
        }else {
            this.handleAutoTimeValue(this.handleGetGroupQueryList)
        }
    };
    handleClearInput =()=>{
        this.setState({
            searchValue: ''
        })
    };
    handleChange = (e) => {
        this.setState({
            searchValue: e.target.value
        });
    };
    handleSearchSubmit = () => {
        this.handleGetGroupQueryList()
    };
    handleSelect = (activePage) => {
        this.setState({
            activePage
        },()=>{
            this.handleGetGroupQueryList()
        })
    };
    handleOrgClick =(org)=>{
        let { searchValue, endTime, startTime, activePage} = this.state;
        startTime =Date.parse(startTime);
        endTime =Date.parse(endTime);
        let params = {
            start_time:startTime,
            end_time:endTime,
            pk_org:org.pkOrg,
            orgName:org.orgName,
            searchValue:searchValue,
            activePage,
            showBreadcrumb:3
        };
        sessionStorage.setItem('fromGroupData',JSON.stringify(params));
        sessionStorage.setItem('copyFromGroupData',JSON.stringify(params));
        window.location.href = encodeURI(vendorsSetUrl('/dataanalysis.html',{ page_state:1 }));
    };
    getAutoStartTime =(newTime)=>{
        let startTime = newTime - 29*24*60*60*1000;
        startTime = vendorsFmtDate(startTime);
        return startTime
    };
    handleAutoTimeValue =(callback)=>{
        let newTime = new Date().getTime();
        let endTime = vendorsFmtDate(newTime);
        let startTime = this.getAutoStartTime(newTime);
        this.setState({
            startTime,
            endTime
        });
        callback&&callback([startTime, endTime]);
    };
    setRowKey =(record,index)=>{
        return index
    };
    onTimeChange=(timeArr)=>{
        let startTime = vendorsFmtDate(timeArr[0]);
        let endTime = vendorsFmtDate(timeArr[1]);
        this.setState({
            startTime,
            endTime
        },()=>{
            let {startTime,endTime} = this.state;
            this.handleGetGroupQueryList([startTime, endTime])
        })
    };
    render() {
        let { startTime, endTime, activePage, searchValue, columns, tableData, billCount, picCount, count, limit } = this.state;
        return (
            <App>
                <div className="group-container">
                    <div className="group-header clearfix">
                        <h1 className="group-header__title">集团查看</h1>
                        <div className='group-header__choosetime clearfix'>
                            <div className="ghc-start-time">
                                <RangePicker
                                    startTime ={startTime}
                                    endTime={endTime}
                                    onChange={this.onTimeChange}
                                />
                            </div>
                            <Button className="ghc-btn" colors="primary" style={{marginRight:'10px'}} onClick={()=>{this.handleAutoTimeValue(this.handleGetGroupQueryList)}}>近30天</Button>
                        </div>
                    </div>
                    <div className="group-content clearfix">
                        <div className="group-content-header clearfix">
                            <div className="gcheader-search-container clearfix">
                                <FormControl
                                    type="text"
                                    placeholder='请输入组织名称'
                                    className='quality__search'
                                    onChange={this.handleChange}
                                    value={searchValue}
                                />
                                {searchValue?<span
                                                    className="clear-input-content"
                                                    onClick={this.handleClearInput}>
                                                        x
                                                </span>:
                                    null}
                                <Button
                                    className={this.state.focusColor + ' ' + 'quality__btn' + ' ' + 'btn_style_format'}
                                    onClick={this.handleSearchSubmit}>
                                    <Icon type="uf-search-light-2"/>
                                </Button>
                            </div>
                            <div className="gcheader-count clearfix">
                                <div className="gcheader-count-bill">
                                    <span>单据总数:&nbsp;</span>
                                    <span>{`${billCount}张`}</span>
                                </div>
                                <div className="gcheader-count-img">
                                    <span>图片总数:&nbsp;</span>
                                    <span>{`${picCount}张`}</span>
                                </div>
                            </div>
                        </div>
                        <div className="group-content-table-container">
                            <Table
                                columns={columns}
                                data={tableData}
                                emptyText={() => '暂无数据'}
                                scroll={{y: 460}}
                                bordered
                                rowKey={this.setRowKey}
                            />
                        </div>
                        <div className="group-content-pagination-container">
                            < Pagination
                                first
                                last
                                prev
                                next
                                boundaryLinks
                                maxButtons={5}
                                items={Math.ceil(count/limit)}
                                activePage={activePage}
                                onSelect={this.handleSelect}
                            />
                        </div>
                    </div>
                </div>
            </App>
        )
    }
}